
package com.bear.net.httpclient;

import com.bear.net.httpclient.util.LogUtil;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.os.Message;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

/**
 * HTTP请求类
 * 
 * @author yinghui.hong
 */
public class HttpRequest {
    private static final String TAG = "HttpRequest";

    /**
     * 加密解密使用的KEY
     */
//    private static String ENCRYPT_KEY = "hjg7de0y";

    /**
     * 发送的JSON串对应的KEY
     */
    private static String MESSAGE_KEY = "messageValue";

    /**
     * 发送的JSON串对应的KEY
     */
//    private static String SESSIONID_KEY = "sessionId";
    
    private static String IMEI = "imei";
    

//    /**
//     * POST方式请求
//     * 
//     * @param url 接口地址
//     * @param handler 用来发送Message对象
//     * @param requestPackage 
//     *            发送的请求数据包，e.g.{"req":[{"reqtype":"login","phone":"13599050189",
//     *            "pwd":"111111"}]}
//     */
//    protected static void startThreadForPost(final String url, final Handler handler,
//            final String requestPackage) {
//        new Thread() {
//
//            @Override
//            public void run() {
//
//                Message message = doPost(url, requestPackage);
//                handler.sendMessage(message);
//            }
//
//        }.start();
//    }
//
//    /**
//     * POST方式请求
//     * 
//     * @param url 接口地址
//     * @param handler 用来发送Message对象
//     * @param requestPackage 
//     *            发送的请求数据包，e.g.{"req":[{"reqtype":"login","phone":"13599050189",
//     *            "pwd":"111111"}]}
//     * @param messageKey 发送的请求数据包对应的KEY e.g."message"
//     */
//    protected static void startThreadForPost(final String url, final Handler handler,
//            final String requestPackage, final String messageKey) {
//        new Thread() {
//
//            @Override
//            public void run() {
//
//                Message message = doPost(url, requestPackage, messageKey);
//                handler.sendMessage(message);
//            }
//
//        }.start();
//    }

    /**
     * 以POST方式请求服务器，设置为public是方便单元测试。默认messageKey为"message"
     * 
     * @param url 接口地址
     * @param requestPackage 
     *            发送的请求数据包，e.g.{"req":[{"reqtype":"login","phone":"13599050189",
     *            "pwd":"111111"}]}
     * @param imeiMd5 deviceId md5加密
     * @return Message对象
     */
    public static Message doPost(String url, String requestPackage,String imeiMd5) {
        return doPost(url, requestPackage, MESSAGE_KEY,imeiMd5);
    }

    /**
     * 以POST方式请求服务器，设置为public是方便单元测试。
     * 
     * @param url 接口地址
     * @param requestPackage 
     *            发送的请求数据包，e.g.{"req":[{"reqtype":"login","phone":"13599050189",
     *            "pwd":"111111"}]}
     * @param messageKey 发送的请求数据包对应的KEY e.g."message"
     * @return Message对象
     */
    public static Message doPost(String url, String requestPackage, String messageKey,String imeiMd5) {
        Message message = Message.obtain();
        try {
            LogUtil.i(TAG, "REQUEST URL IS --- " + url);
            HttpClient httpClient = new DefaultHttpClient();
            httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);
            httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);
            HttpPost httpPost = new HttpPost(url);

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            String afterEnStr = requestPackage;
            if (afterEnStr != null && !afterEnStr.trim().equals("")) {
                params.add(new BasicNameValuePair(messageKey, afterEnStr));
            }
            params.add(new BasicNameValuePair(IMEI,imeiMd5));
            httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            HttpResponse httpResponse = httpClient.execute(httpPost);
            int responseCode = httpResponse.getStatusLine().getStatusCode();
            message.arg1 = responseCode;
            if (responseCode == HttpStatus.SC_OK) {// FUNO FIX OK接收到信息需要解密
                String responseStr = EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8);
                message.obj = responseStr;
            }
        } catch (ConnectTimeoutException e) {
            // 包括请求超时和响应超时
            Log.e(TAG, "******************ConnectTimeoutException****************\n" + e.toString());
            message.arg1 = HttpResCode.TIME_OUT;
        } catch (Exception e) {
            // 获取：加密、解密导致的网络传输异常IllegalBlockSizeException，编码异常。统一命名为服务器异常
            Log.e(TAG, "*********************error ******************\n" + e.toString());
            message.arg1 = HttpResCode.SERVER_ERROR;
        }
        
        return message;
    }
}
